//
//  UIViewController+FilePreview.m
//  YHSuoShi
//
//  Created by 000 on 2020/11/17.
//  Copyright © 2020 林宁宁. All rights reserved.
//

#import "UIViewController+FilePreview.h"
#import <objc/runtime.h>


@implementation UIViewController (FilePreview)


-(UIDocumentInteractionController *)previewService{
    return objc_getAssociatedObject(self, @selector(previewService));
}
-(void)setPreviewService:(UIDocumentInteractionController *)previewService{
    objc_setAssociatedObject(self, @selector(previewService), previewService, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(BOOL)needClearWhenClose{
    return [objc_getAssociatedObject(self, @selector(needClearWhenClose)) boolValue];
}
-(void)setNeedClearWhenClose:(BOOL)needClearWhenClose{
    objc_setAssociatedObject(self, @selector(needClearWhenClose), @(needClearWhenClose), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


- (void)yh_preview:(NSURL *)fileurl{
    [self yh_preview:fileurl needClean:NO];
}
- (void)yh_preview:(NSURL *)fileurl needClean:(BOOL)needClearWhenClose{
    
    self.previewService = [UIDocumentInteractionController interactionControllerWithURL:fileurl];
    self.previewService.delegate = self;
    self.needClearWhenClose = needClearWhenClose;
    [self.previewService presentPreviewAnimated:YES];
}

- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    return self;
}
- (UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller{
    return self.view;
}
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller{
    return self.view.frame;
}
- (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller{
    if(self.needClearWhenClose){
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSFileManager * filemanager = [NSFileManager defaultManager];
            [filemanager removeItemAtURL:controller.URL error:nil];
        });
    }
}

@end
